﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Drawing.Printing;
using System.IO;
using System.Data.SQLite;
using System.Security.Cryptography.X509Certificates;
using System.Data.Common;
using System.Net.WebSockets;
using System.Net.Sockets;
using System.Security.Authentication;
using System.Net;
using Newtonsoft.Json;

namespace SocketClient
{
    class NetApi
    {
        private SqlLiteUtils sqlLite;
        private string domain;
        //OutputMsg outMsg = new OutputMsg();

        #region 操作函数代码块
        public void InitDomainConfig()
        {
            // 指定配置文件的路径
            string configFilePath = GValues.configPath; //"E:\\Program Files\\Autodesk\\AutoCAD 2014\\erptestdll\\config.txt";
            try
            {
                // 读取文本文件的所有行
                string[] lines = File.ReadAllLines(configFilePath);

                // 遍历每一行并处理配置信息
                foreach (string line in lines)
                {
                    // 假设配置文件的每一行都是以"键=值"的格式存储
                    string[] keyValue = line.Split('=');
                    if (keyValue.Length == 2)
                    {
                        string key = keyValue[0].Trim();
                        string value = keyValue[1].Trim();
                        // 在这里处理配置信息，例如存储到字典或使用
                        if (key == "domain")
                        {
                            domain = value;
                            GValues.domain = value;
                        }
                        try
                        {
                            if (key == "domainLink")
                            {
                                GValues.domainLink = value;
                            }
                            if (key == "searchPath")
                            {
                                GValues.searchPath = value;
                            }
                            if (key == "printName")
                            {
                                GValues.printName = value;
                            }
                        }
                        catch (System.Exception e)
                        {
                            LogHelper.WriteLog(e.ToString(),null);
                        }
                    }
                }
            }
            catch (IOException e)
            {
                LogHelper.WriteLog("读取配置文件时发生错误: " + e.Message,null);
            }

        }

        public void getUserInfo()
        {
            try
            {
                string sPassword = "";
                sqlLite = new SqlLiteUtils();
                string sql = "select account,password,domainid,token from user";
                SQLiteDBHelper db = new SQLiteDBHelper(GValues.dbpath);
                using (SQLiteDataReader reader = db.ExecuteReader(sql, null))
                {
                    while (reader.Read())
                    {
                        GValues.account = reader.GetString(0);
                        sPassword = reader.GetString(1);
                        GValues.tenant = reader.GetString(2);
                        GValues.token = reader.GetString(3);
                    }
                }
                GValues.password = StringSecurity.DESDecrypt(sPassword);
            }
            catch (System.Exception e)
            {
                LogHelper.WriteLog("SqlLite读取数据表时发生错误: " + e.Message,null);
            }
        }
        public void GetDomainTenant()
        {
            int i = 0;
            Http.CreateHttpClient().GetAsync(GValues.domainLink + "saas/data/get?domain=" + domain, new Action<Http.HttpResp>((r) =>
            {
                var responCode = Convert.ToInt32(r.Code);
                if (responCode == 200) //访问成功
                {
                    GValues.tenant = r.AckStr();
                }
                else
                {
                    LogHelper.WriteLog("Net获取租户信息发生错误: " + r.Code + " " + " " + responCode + " " + r.Error,null);
                }
            }));
        }
        public void changePassword(String account, String password)
        {
            try
            {
                SqlLiteUtils sqlLite = new SqlLiteUtils();
                //sqlLite.createDb();
                //sqlLite.insertData(GValues.account, GValues.password, GValues.tenant, GValues.token);
                string commandString = "update user set password = '" + StringSecurity.DESEncrypt(password) + "' where account = '" + account + "';";
                sqlLite.updateData(commandString);
            }
            catch (Exception e)
            {
                LogHelper.WriteLog("SqlLite更新密码数据时发生错误: " + e.Message,null);
            }
        }
        //
        //从本地发起登入系统
        //
        public void localLogin()
        {
            string postData = "{\"username\":\"" + GValues.account + "\",\"password\":\"" + GValues.password+ "\",\"captchaFlag\":\"true\"}";
            Http.CreateHttpClient(GValues.domainLink + "sys/login", GValues.tenant, GValues.token).PostAsync(postData, new Action<Http.HttpResp>((r) =>
            {
                var responCode = Convert.ToInt32(r.Code);
                if (responCode == 200) //访问成功
                {
                    ResponResult<LoginDTO> responResult = JsonConvert.DeserializeObject<ResponResult<LoginDTO>>(r.AckStr());
                    if (responResult.success)
                    {
                        GValues.token = responResult.result.token;
                        SqlLiteUtils sqlLite = new SqlLiteUtils();
                        //sqlLite.createDb();
                        //sqlLite.insertData(GValues.account, GValues.password, GValues.tenant, GValues.token);
                        string commandString = "update user set token = '" + GValues.token + "' where account = '" + GValues.account + "';";
                        sqlLite.updateData(commandString);
                        //GValues.globalUrl = GValues.domainLink.Replace("http", "ws").Replace("https", "wss") + "websocket/" + GValues.tenant + "-" + GValues.account + "-print";
                        LogHelper.WriteLog("成功登入系统");
                    }
                    else
                    {
                        LogHelper.WriteLog("登入系统发生错误: " + responResult.code + " " + responResult.message,null);
                    }
                }
                else
                {
                    LogHelper.WriteLog("登入系统发生错误: " + r.Code + " " + " " + responCode + " " + r.Error,null);
                }
            }));
        }
        #endregion
    }
}
